'use strict'

const db = uniCloud.database()
const collection = db.collection('milk-records')

exports.main = async (event, context) => {
  const { action, data } = event

  try {
    let result

    switch (action) {
      case 'add':
        // 验证必要参数
        if (!data) {
          throw new Error('缺少数据参数')
        }
        if (
          !data.amount ||
          typeof data.amount !== 'number' ||
          data.amount <= 0
        ) {
          throw new Error('奶量必须是大于0的数字')
        }
        if (!data.date || !/^\d{4}-\d{2}-\d{2}$/.test(data.date)) {
          throw new Error('日期格式必须是YYYY-MM-DD')
        }
        if (
          !data.time ||
          !/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/.test(data.time)
        ) {
          throw new Error('时间格式必须是HH:MM')
        }

        result = await collection.add({
          ...data,
          create_time: new Date(),
          update_time: new Date(),
        })
        break

      case 'get':
        // 获取指定日期的记录
        if (!data || !data.date) {
          throw new Error('查询指定日期记录时必须提供日期参数')
        }
        if (!/^\d{4}-\d{2}-\d{2}$/.test(data.date)) {
          throw new Error('日期格式必须是YYYY-MM-DD')
        }

        const { date } = data
        result = await collection.where({ date }).orderBy('time', 'asc').get()
        break

      case 'update':
        // 更新记录
        if (!data || !data.id || !data.updateData) {
          throw new Error('更新记录需要提供id和updateData参数')
        }

        const { id, updateData } = data
        result = await collection.doc(id).update({
          ...updateData,
          update_time: new Date(),
        })
        break

      case 'delete':
        // 删除记录
        if (!data || !data.id) {
          throw new Error('删除记录需要提供id参数')
        }

        const { id: deleteId } = data
        result = await collection.doc(deleteId).remove()
        break

      case 'batchDelete':
        // 批量删除记录
        if (!data || !data.ids || !Array.isArray(data.ids)) {
          throw new Error('批量删除需要提供ids数组参数')
        }
        if (data.ids.length === 0) {
          throw new Error('删除记录列表不能为空')
        }
        if (data.ids.length > 10) {
          throw new Error('单次最多删除10条记录')
        }

        const deleteResults = []
        const { ids } = data

        for (const id of ids) {
          try {
            const deleteResult = await collection.doc(id).remove()
            deleteResults.push({
              id: id,
              success: true,
              deleted: deleteResult.deleted,
            })
          } catch (error) {
            deleteResults.push({
              id: id,
              success: false,
              error: error.message,
            })
          }
        }

        const successCount = deleteResults.filter((r) => r.success).length
        const failCount = deleteResults.filter((r) => !r.success).length

        result = {
          data: {
            results: deleteResults,
            successCount: successCount,
            failCount: failCount,
            totalProcessed: deleteResults.length,
          },
        }
        break

      case 'findRecords':
        // 智能查询匹配记录 - 用于删除前的记录查找
        if (!data) {
          throw new Error('查询参数不能为空')
        }

        const {
          date: searchDate,
          timeRange,
          exactTime,
          amount,
          feedingType,
          limit = 10,
          sortBy = 'time',
          sortOrder = 'desc',
        } = data

        // 构建查询条件对象 - 修复多个where覆盖问题
        const whereConditions = {}

        // 按日期筛选
        if (searchDate) {
          if (!/^\d{4}-\d{2}-\d{2}$/.test(searchDate)) {
            throw new Error('日期格式必须是YYYY-MM-DD')
          }
          whereConditions.date = searchDate
        }

        // 按精确时间筛选
        if (exactTime) {
          if (!/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/.test(exactTime)) {
            throw new Error('时间格式必须是HH:MM')
          }
          whereConditions.time = exactTime
        }

        // 按时间范围筛选（用于"10点左右"这类模糊查询）
        if (timeRange && timeRange.start && timeRange.end) {
          whereConditions.time = db.command
            .gte(timeRange.start)
            .and(db.command.lte(timeRange.end))
        }

        // 按奶量筛选
        if (amount) {
          if (typeof amount !== 'number' || amount <= 0) {
            throw new Error('奶量必须是大于0的数字')
          }
          whereConditions.amount = amount
        }

        // 按喂养类型筛选
        if (feedingType) {
          const validTypes = ['bottle_breast', 'bottle_formula', 'direct']
          if (!validTypes.includes(feedingType)) {
            throw new Error('喂养类型不正确')
          }
          whereConditions.feeding_type = feedingType
        }

        // 应用查询条件 - 一次性设置所有条件
        let query = collection
        if (Object.keys(whereConditions).length > 0) {
          query = query.where(whereConditions)
        }

        // 排序和限制
        if (sortBy === 'time') {
          query = query.orderBy('time', sortOrder)
        } else if (sortBy === 'amount') {
          query = query.orderBy('amount', sortOrder)
        } else {
          query = query.orderBy('create_time', sortOrder)
        }

        if (limit && limit > 0 && limit <= 100) {
          query = query.limit(limit)
        }

        const findResult = await query.get()

        result = {
          data: {
            records: findResult.data || [],
            count: findResult.data ? findResult.data.length : 0,
            query: data,
          },
        }
        break

      case 'findSimilarRecords':
        // 查找相似记录 - 用于智能建议
        if (!data) {
          throw new Error('查询参数不能为空')
        }

        const {
          date: similarDate,
          time: targetTime,
          timeRange: similarTimeRange = 30, // 默认前后30分钟
        } = data

        const suggestions = []

        if (similarDate && targetTime) {
          // 解析目标时间
          const [targetHour, targetMinute] = targetTime.split(':').map(Number)
          const targetMinutes = targetHour * 60 + targetMinute

          // 计算时间范围
          const startMinutes = Math.max(0, targetMinutes - similarTimeRange)
          const endMinutes = Math.min(1439, targetMinutes + similarTimeRange) // 23:59

          const startTime = `${Math.floor(startMinutes / 60)
            .toString()
            .padStart(2, '0')}:${(startMinutes % 60)
            .toString()
            .padStart(2, '0')}`
          const endTime = `${Math.floor(endMinutes / 60)
            .toString()
            .padStart(2, '0')}:${(endMinutes % 60).toString().padStart(2, '0')}`

          // 查找时间范围内的记录
          const rangeQuery = collection
            .where({
              date: similarDate,
              time: db.command.gte(startTime).and(db.command.lte(endTime)),
            })
            .orderBy('time', 'asc')

          const rangeResult = await rangeQuery.get()

          for (const record of rangeResult.data || []) {
            const [recordHour, recordMinute] = record.time
              .split(':')
              .map(Number)
            const recordMinutes = recordHour * 60 + recordMinute
            const timeDiff = Math.abs(recordMinutes - targetMinutes)

            suggestions.push({
              ...record,
              timeDifference: timeDiff,
              matchScore: Math.max(0, 100 - timeDiff * 2), // 时间越近分数越高
            })
          }
        }

        // 按匹配分数排序
        suggestions.sort((a, b) => b.matchScore - a.matchScore)

        result = {
          data: {
            suggestions: suggestions.slice(0, 5), // 最多返回5条建议
            targetTime: targetTime,
            searchRange: similarTimeRange,
            query: data,
          },
        }
        break

      case 'restoreRecords':
        // 恢复删除的记录
        if (!data || !data.records || !Array.isArray(data.records)) {
          throw new Error('恢复记录需要提供records数组参数')
        }

        const { records: restoreRecords } = data
        const restoreResults = []

        for (const record of restoreRecords) {
          try {
            // 重新插入记录（去掉_id让数据库自动生成新的）
            const { _id, ...recordData } = record
            recordData.create_time = new Date()
            recordData.source = recordData.source || 'ai_assistant_restore'

            const insertResult = await collection.add(recordData)
            restoreResults.push({
              success: true,
              id: insertResult.id,
              data: recordData,
            })
          } catch (error) {
            restoreResults.push({
              success: false,
              error: error.message,
              data: record,
            })
          }
        }

        const restoreSuccessCount = restoreResults.filter(
          (r) => r.success
        ).length
        const restoreFailCount = restoreResults.filter((r) => !r.success).length

        result = {
          data: {
            results: restoreResults,
            successCount: restoreSuccessCount,
            failCount: restoreFailCount,
            totalProcessed: restoreResults.length,
          },
        }
        break

      case 'getDateRange':
        // 获取日期范围内的记录
        if (!data || !data.startDate || !data.endDate) {
          throw new Error('查询日期范围记录需要提供startDate和endDate参数')
        }

        const { startDate, endDate } = data
        result = await collection
          .where({
            date: db.command.gte(startDate).and(db.command.lte(endDate)),
          })
          .orderBy('date', 'desc')
          .orderBy('time', 'asc')
          .get()
        break

      case 'getAll':
        // 获取所有记录
        result = await collection
          .orderBy('date', 'desc')
          .orderBy('time', 'desc')
          .limit(100) // 限制最多返回100条记录，避免数据过多
          .get()
        break

      case 'getStatistics':
        // 获取统计信息
        if (!data || !data.statDate) {
          throw new Error('查询统计信息需要提供statDate参数')
        }
        if (!/^\d{4}-\d{2}-\d{2}$/.test(data.statDate)) {
          throw new Error('统计日期格式必须是YYYY-MM-DD')
        }

        const { statDate } = data
        const statsResult = await collection.where({ date: statDate }).get()

        const records = statsResult.data
        const totalAmount = records.reduce(
          (sum, record) => sum + record.amount,
          0
        )
        const avgAmount =
          records.length > 0 ? Math.round(totalAmount / records.length) : 0

        result = {
          data: {
            totalAmount,
            avgAmount,
            recordCount: records.length,
            records: records.sort((a, b) => a.time.localeCompare(b.time)),
          },
        }
        break

      default:
        throw new Error(`未知的操作类型: ${action}`)
    }

    return {
      success: true,
      data: result.data || result,
      message: '操作成功',
    }
  } catch (error) {
    console.error('云函数执行错误:', error)
    return {
      success: false,
      error: error.message,
      message: `操作失败: ${error.message}`,
    }
  }
}
